﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using System.Net;
using System.Web;
using System.Web.Mvc;
using LanDBom.Models;
using static System.Windows.Forms.AxHost;
using Newtonsoft.Json;
using Kingdee.BOS.WebApi.Client;
using Kingdee.BOS.WebApi.DataEntify;
using Microsoft.Office.Interop.Excel;
using System.Text;
using Org.BouncyCastle.Crypto;
using Newtonsoft.Json.Linq;
using OfficeOpenXml;
using System.IO;
using Kingdee.BOS.Util;
using OfficeOpenXml.Drawing.Slicer.Style;
using FastReport.Barcode;
using NPOI.SS.Formula.Functions;
using static NPOI.HSSF.Record.UnicodeString;
using System.Windows.Forms;
using System.Reflection.PortableExecutable;

namespace LanDBom.Controllers
{
    public class FormationsController : Controller
    {
        private LDbaseEntities db = new LDbaseEntities();
        Add_CL AC = new Add_CL();
        // GET: Formations
        public ActionResult Index(string shen = "", string ming = "", string shi = "", int shujina = 0, int state = 0, string WUliao = "")
        {

            var formation = db.Formation.Include(f => f.mateial).Include(f => f.Providers).ToList();
            if (shen != "")
            {
                formation = formation.Where(s => s.FM_name.Contains(shen)).ToList();
            }
            if (ming != "")
            {
                formation = formation.Where(s => s.FM_bai.Contains(ming)).ToList();
            }
            if (shi != "")
            {
                formation = formation.Where(s => s.FM_ji == shi).ToList();
            }
            if (WUliao != "")
            {
                if (WUliao == "ERP")
                {
                    formation = formation.Where(s => !s.FM_bai.Contains("WL")).ToList();
                }
                else
                {
                    formation = formation.Where(s => s.FM_bai.Contains("WL")).ToList();
                }
            }

            var SHIyong = formation;
            if (state == 1)
            {
                var HJ = SHIyong.Count().ToString();
                return Content(HJ);
            }
            if (state == 2)
            {
                formation = formation.OrderBy(s => s.FM_ID).Skip(10 * shujina).Take(10).ToList();
                ERPZDJ(WUliao, formation);
                var HJ = from a in formation select new { a.FM_ID, a.FM_bai, a.FM_name, a.FM_gg, a.FM_bmcl, a.FM_ycl, a.FM_zx, a.FM_yj, a.FM_ej, a.FM_price, PR_name = a.Providers == null ? "" : a.Providers.PR_name, a.FM_long, a.FM_kuan, a.FM_kong, a.FM_ms };
                JsonSerializerSettings settings = new JsonSerializerSettings();
                string jsongStr = JsonConvert.SerializeObject(HJ, settings);
                return Content(jsongStr, "application/json");
            }
            return View(formation);
        }

        private void ERPZDJ(string WUliao, List<Formation> formation)
        {
            if (WUliao != "")
            {
                var shn = "";
                var dateT = DateTime.Now.ToString("yyyy-MM-dd H:mm:ss");
                //用于记录结果
                var client = new K3CloudApi();
                StringBuilder Info = new StringBuilder();
                string formId = "PUR_PriceCategory";
                //业务对象标识
                var FMA = new List<Formation>();
                string fieldKeys = "FPrice,FTaxPrice,FMaterialId.FNumber";//客户 编码 联系电话 邮箱 通讯地址 备注 省份
                var shunji = 0;
                foreach (var item in formation)
                {
                    var shin = item.FM_bai;//编码
                    shunji++;
                    if (shunji > 100)
                    {
                        shunji = GX_shuj_A(dateT, client, formId, FMA, fieldKeys);
                        foreach (var l in formation)
                        {
                            var shu = l.FM_bai;
                            var s = FMA.Where(x => x.FM_bai == shu).FirstOrDefault();
                            if (s != null)
                            {
                                l.FM_long = s.FM_long;
                                l.FM_kuan = s.FM_kuan;
                                l.FM_kong = s.FM_kong;
                                l.FM_ms = s.FM_ms;
                            }
                        }
                        FMA.Clear();
                    }
                    else
                    {
                        FMA.Add(item);
                        if (item.Equals(formation.Last()))
                        {
                            shunji = GX_shuj_A(dateT, client, formId, FMA, fieldKeys);
                            foreach (var l in formation)
                            {
                                var shu = l.FM_bai;
                                var s = FMA.Where(x => x.FM_bai == shu).FirstOrDefault();
                                if (s != null)
                                {
                                    l.FM_long = s.FM_long;
                                    l.FM_kuan = s.FM_kuan;
                                    l.FM_kong = s.FM_kong;
                                    l.FM_ms = s.FM_ms;
                                }
                            }
                            FMA.Clear();
                        }
                    }

                }
            }
        }

        private int GX_shuj_A(string dateT, K3CloudApi client, string formId, List<Formation> FMA, string fieldKeys)
        {
            int shunji;
            var shuj = "";
            foreach (var item2 in FMA)
            {
                var binas = item2.FM_bai;
                if (item2.Equals(FMA.Last()))
                {
                    shuj += "'" + binas + "'";
                }
                else
                {
                    shuj += "'" + binas + "',";
                }
            }
            string Filter = "FMaterialId.FNumber in (" + shuj + ") and FForbidStatus='A' and FDisableStatus='B' and FEntryExpiryDate>'" + dateT + "' and FCreateOrgId.FNumber='10.01'";
            //请求参数，示例使用的是SDK提供的模板类，还可以使用字符串拼接等方式 FEntryExpiryDate
            var param = new QueryParam()
            {
                FormId = formId,
                FieldKeys = fieldKeys,
                FilterString = Filter,
                TopRowCount = 0,
                StartRow = 0,
                Limit = 500,
            };
            //调用接口
            var result = client.ExecuteBillQuery(param.ToJson());
            //计算最小值
            if (result.Count() > 0)
            {
                var resultJObject = JArray.Parse(JsonConvert.SerializeObject(result[0]));
                var queryNode = resultJObject.SelectToken("$..IsSuccess");
                if (queryNode == null)
                {
                    var Dt = new System.Data.DataTable();
                    Dt.Columns.Add("Dan", typeof(double));
                    Dt.Columns.Add("Han", typeof(double));
                    Dt.Columns.Add("BM", typeof(string));
                    //转换成datatable
                    foreach (var rfe in result)
                    {
                        Dt.Rows.Add(rfe[0], rfe[1], rfe[2]);
                    }
                    foreach (var kool in FMA)
                    {
                        var WLB = kool.FM_bai;
                        var shun = Dt.Select("BM='" + WLB + "'");
                        var ZuiminD = new List<double>();
                        var ZuiminH = new List<double>();
                        foreach (var d in shun)
                        {
                            ZuiminD.Add((double)d[0]);
                            ZuiminH.Add((double)d[1]);
                        }
                        if (ZuiminD.Count() > 0)
                        {
                            var ZD = ZuiminD.Min();
                            var ZD1 = ZuiminH.Min();
                            kool.FM_long = (decimal?)ZD;
                            kool.FM_kuan = (decimal?)ZD1;
                        }
                        else
                        {
                            kool.FM_long = null;
                            kool.FM_kuan = null;
                        }
                        ///查询BOM和app
                        var shund = db.BOMini.Where(s => s.BOM2_bian.Contains("ERP") && s.BOM2_liao == WLB).FirstOrDefault();//单行
                        var BbianH = shund == null ? "" : shund.BOM2_bian;
                        var Cxapp = db.Applications.Where(s => s.AP_bian == BbianH).FirstOrDefault();
                        kool.FM_kong = Cxapp == null ? "" : Cxapp.AP_bian;
                        kool.FM_ms = Cxapp == null ? "" : Cxapp.AP_ren;
                    }
                }
                else
                {
                    foreach (var kool in FMA)
                    {
                        FAWM(kool);
                    }
                }
            }
            else
            {
                foreach (var kool in FMA)
                {
                    FAWM(kool);
                }
            }
            shunji = 0;
            return shunji;
        }

        private void FAWM(Formation item)
        {
            var bian = item.FM_bai;
            var shund = db.BOMini.Where(s => s.BOM2_bian.Contains("ERP") && s.BOM2_liao == bian).FirstOrDefault();//单行
            var BbianH = shund == null ? "" : shund.BOM2_bian;
            var Cxapp = db.Applications.Where(s => s.AP_bian == BbianH).FirstOrDefault();
            item.FM_kong = Cxapp == null ? "" : Cxapp.AP_bian;
            item.FM_ms = Cxapp == null ? "" : Cxapp.AP_ren;
            item.FM_long = null;
            item.FM_kuan = null;
        }

        // GET: Formations/Details/5
        public async Task<ActionResult> Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Formation formation = await db.Formation.FindAsync(id);
            if (formation == null)
            {
                return HttpNotFound();
            }
            return View(formation);
        }

        // GET: Formations/Create
        public ActionResult Create()
        {
            ViewBag.MA_ID = new SelectList(db.mateial, "MA_ID", "MA_fne");
            ViewBag.PR_ID = new SelectList(db.Providers, "PR_ID", "PR_name");
            return View();
        }

        // POST: Formations/Create
        // 为了防止“过多发布”攻击，请启用要绑定到的特定属性；有关
        // 更多详细信息，请参阅 https://go.microsoft.com/fwlink/?LinkId=317598。
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Create([Bind(Include = "FM_ID,FM_bai,FM_name,MA_ID,FM_long,FM_kuan,FM_gao,FM_price,PR_ID,FM_ji,FM_Zhuang")] Formation formation)
        {
            if (ModelState.IsValid)
            {
                db.Formation.Add(formation);
                await db.SaveChangesAsync();
                return RedirectToAction("Index");
            }

            ViewBag.MA_ID = new SelectList(db.mateial, "MA_ID", "MA_bai", formation.MA_ID);
            ViewBag.PR_ID = new SelectList(db.Providers, "PR_ID", "PR_bian", formation.PR_ID);
            return View(formation);
        }

        // GET: Formations/Edit/5
        public async Task<ActionResult> Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Formation formation = await db.Formation.FindAsync(id);
            if (formation == null)
            {
                return HttpNotFound();
            }
            ViewBag.MA_ID = new SelectList(db.mateial, "MA_ID", "MA_fne", formation.MA_ID);
            ViewBag.PR_ID = new SelectList(db.Providers, "PR_ID", "PR_name", formation.PR_ID);
            return View(formation);
        }

        // POST: Formations/Edit/5
        // 为了防止“过多发布”攻击，请启用要绑定到的特定属性；有关
        // 更多详细信息，请参阅 https://go.microsoft.com/fwlink/?LinkId=317598。
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Edit([Bind(Include = "FM_ID,FM_bai,FM_name,MA_ID,FM_long,FM_kuan,FM_gao,FM_price,PR_ID,FM_ji,FM_Zhuang")] Formation formation)
        {
            if (ModelState.IsValid)
            {
                db.Entry(formation).State = EntityState.Modified;
                await db.SaveChangesAsync();
                return RedirectToAction("Index");
            }
            ViewBag.MA_ID = new SelectList(db.mateial, "MA_ID", "MA_bai", formation.MA_ID);
            ViewBag.PR_ID = new SelectList(db.Providers, "PR_ID", "PR_bian", formation.PR_ID);
            return View(formation);
        }

        // GET: Formations/Delete/5
        public async Task<ActionResult> Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Formation formation = await db.Formation.FindAsync(id);
            if (formation == null)
            {
                return HttpNotFound();
            }
            return View(formation);
        }

        // POST: Formations/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> DeleteConfirmed(int id)
        {
            Formation formation = await db.Formation.FindAsync(id);
            db.Formation.Remove(formation);
            await db.SaveChangesAsync();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }

        //获取物料库的数量
        public ActionResult FomShu(int steate = 0)
        {
            if (steate == 1)
            {
                var inde = db.Formation.Where(s => s.FM_bai.Contains("WL")).ToList();
                var S = inde[inde.Count - 1].FM_ID.ToString();
                return Content(S.ToString());
            }
            return View();
        }
        //传递值ERP物料
        public ActionResult ErpCdi(int id)
        {
            var BOmin = db.Formation.Find(id);
            var fenzhu = BOmin.FM_ej;//二级类别
            var shuc = HUDNH(fenzhu);
            var fenzhu12 = BOmin.FM_ji;
            var HU = db.Freht.Where(s => s.Fre_beizhu == fenzhu12).FirstOrDefault().Fre_shijian;
            var client = new K3CloudApi();
            //用于记录结果
            StringBuilder Info = new StringBuilder();
            //业务对象标识
            string formId = "BD_MATERIAL";
            //
            string Wljson = "{\"NeedUpDateFields\":[],\"NeedReturnFields\":[],\"IsDeleteEntry\":\"true\",\"SubSystemId\":\"\",\"IsVerifyBaseDataField\":\"false\",\"IsEntryBatchFill\":\"true\",\"ValidateFlag\":\"true\",\"NumberSearch\":\"true\",\"IsAutoAdjustField\":\"false\",\"InterationFlags\":\"\",\"IgnoreInterationFlag\":\"\",\"IsControlPrecision\":\"false\",\"ValidateRepeatJson\":\"false\",\"Model\":{\"FMATERIALID\":0,\"FCreateOrgId\":{\"FNumber\":\"10.01\"},\"FUseOrgId\":{\"FNumber\":\"10.01\"},\"FName\":\"" + BOmin.FM_name + "\",\"FSpecification\":\"" + BOmin.FM_gg + "\",\"FMaterialGroup\":{\"FNumber\":\"" + shuc + "\"},\"FDSMatchByLot\":false,\"FImgStorageType\":\"B\",\"FIsSalseByNet\":false,\"F_land_ZHOUS\":0,\"F_land_KFL\":0,\"F_land_CPZJ\":0,\"FIsHandleReserve\":true,\"F_land_DBSL\":0,\"F_land_ZDFK\":0,\"F_land_MTSL\":0,\"F_land_ZYMF\":0,\"F_land_MJ\":0,\"F_land_PYQD\":0,\"F_land_KJ\":0,\"F_land_MOS\":0,\"F_land_ZYKD\":0,\"F_land_LX\":{\"FNumber\":\"\"},\"F_land_NAIPO\":0,\"F_land_H\":0,\"F_land_MS\":0,\"F_land_MD\":0,\"F_land_KZ\":0,\"F_land_MF\":0,\"F_land_ZXKY\":0,\"F_land_CPZX\":0,\"F_land_YD\":0,\"F_land_BY\":0,\"F_land_NJ\":0,\"F_land_MaterialQuality\":\"\",\"F_land_TIJ\":0,\"F_land_CFDD\":false,\"F_SMGS_sccs\":0,\"F_SMGS_bkck\":0,\"F_SMGS_m2\":0,\"F_SMGS_dwtj\":0,\"F_SMGS_ysbzgs\":0,\"F_SMGS_mqbzgs\":0,\"F_SMGS_nhbzgs\":0,\"F_SMGS_qfbzgs\":0,\"F_SMGS_sgbzgs\":0,\"F_SMGS_zbfqbs\":0,\"F_SMGS_smjfqbs\":0,\"F_SMGS_njjbs\":0,\"F_SMGS_ddbs\":0,\"F_SMGS_dybs\":0,\"F_SMGS_epebs\":0,\"F_SMGS_tpbs\":0,\"F_SMGS_fczmqbs\":0,\"F_SMGS_fczqzbs\":0,\"F_SMGS_tcjbs\":0,\"F_SMGS_bqdybs\":0,\"F_SMGS_pedbs\":0,\"F_SMGS_mjQty\":0,\"F_SMGS_ybQty\":0,\"F_SMGS__land_CHUOC\":0,\"F_SMGS_qm2Qty\":0,\"F_SMGS_zxms\":0,\"F_SMGS_PACKAGE_QTY\":0,\"FSubHeadEntity\":{\"FIsControlSal\":false,\"FLowerPercent\":0,\"FUpPercent\":0,\"FCalculateBase\":\"0\",\"FMaxSalPrice_CMK\":0,\"FMinSalPrice_CMK\":0,\"FIsAutoRemove\":false,\"FIsMailVirtual\":false,\"FIsFreeSend\":\"0\",\"FTimeUnit\":\"H\",\"FRentFreeDura\":0,\"FPricingStep\":0,\"FMinRentDura\":0,\"FRentBeginPrice\":0,\"FPriceType\":\"0\",\"FRentStepPrice\":0,\"FDepositAmount\":0,\"FLogisticsCount\":0,\"FRequestMinPackQty\":0,\"FMinRequestQty\":0,\"FIsPrinttAg\":false,\"FIsAccessory\":false,\"FUploadSkuImage\":false},\"SubHeadEntity\":{\"FErpClsID\":\"1\",\"FFeatureItem\":\"1\",\"FCategoryID\":{\"FNumber\":\"CHLB01_SYS\"},\"FTaxType\":{\"FNumber\":\"WLDSFL01_SYS\"},\"FTaxRateId\":{\"FNUMBER\":\"SL02_SYS\"},\"FBaseUnitId\":{\"FNumber\":\"" + HU + "\"},\"FIsPurchase\":true,\"FIsInventory\":true,\"FIsSubContract\":false,\"FIsSale\":true,\"FIsProduce\":false,\"FIsAsset\":false,\"FGROSSWEIGHT\":0,\"FNETWEIGHT\":0,\"FWEIGHTUNITID\":{\"FNUMBER\":\"kg\"},\"FLENGTH\":100,\"FWIDTH\":110,\"FHEIGHT\":120,\"FVOLUME\":1320000,\"FVOLUMEUNITID\":{\"FNUMBER\":\"m\"},\"FSuite\":\"0\",\"FCostPriceRate\":0},\"SubHeadEntity1\":{\"FStoreUnitID\":{\"FNumber\":\"Pcs\"},\"FUnitConvertDir\":\"1\",\"FIsLockStock\":true,\"FIsCycleCounting\":false,\"FCountCycle\":\"1\",\"FCountDay\":1,\"FIsMustCounting\":false,\"FIsBatchManage\":false,\"FIsKFPeriod\":false,\"FIsExpParToFlot\":false,\"FExpPeriod\":0,\"FOnlineLife\":0,\"FRefCost\":0,\"FCurrencyId\":{\"FNumber\":\"PRE001\"},\"FIsEnableMinStock\":false,\"FIsEnableMaxStock\":false,\"FIsEnableSafeStock\":false,\"FIsEnableReOrder\":false,\"FMinStock\":0,\"FSafeStock\":0,\"FReOrderGood\":0,\"FEconReOrderQty\":0,\"FMaxStock\":0,\"FIsSNManage\":false,\"FIsSNPRDTracy\":false,\"FSNManageType\":\"1\",\"FSNGenerateTime\":\"1\",\"FBoxStandardQty\":0},\"SubHeadEntity2\":{\"FSaleUnitId\":{\"FNumber\":\"Pcs\"},\"FSalePriceUnitId\":{\"FNumber\":\"Pcs\"},\"FOrderQty\":0,\"FMinQty\":0,\"FMaxQty\":100000,\"FOutStockLmtH\":0,\"FOutStockLmtL\":0,\"FAgentSalReduceRate\":0,\"FIsATPCheck\":false,\"FIsReturnPart\":false,\"FIsInvoice\":false,\"FIsReturn\":true,\"FAllowPublish\":false,\"FISAFTERSALE\":true,\"FISPRODUCTFILES\":true,\"FISWARRANTED\":false,\"FWARRANTY\":0,\"FWARRANTYUNITID\":\"D\",\"FOutLmtUnit\":\"SAL\",\"FIsTaxEnjoy\":false,\"FTaxDiscountsType\":\"0\",\"FUnValidateExpQty\":false},\"SubHeadEntity3\":{\"FBaseMinSplitQty\":0,\"FPurchaseUnitId\":{\"FNumber\":\"Pcs\"},\"FPurchasePriceUnitId\":{\"FNumber\":\"Pcs\"},\"FIsQuota\":false,\"FQuotaType\":\"1\",\"FMinSplitQty\":0,\"FIsVmiBusiness\":false,\"FEnableSL\":false,\"FIsPR\":false,\"FIsReturnMaterial\":true,\"FIsSourceControl\":false,\"FReceiveMaxScale\":0,\"FReceiveMinScale\":0,\"FReceiveAdvanceDays\":0,\"FReceiveDelayDays\":0,\"FPOBillTypeId\":{\"FNUMBER\":\"CGSQD01_SYS\"},\"FAgentPurPlusRate\":0,\"FPrintCount\":1,\"FMinPackCount\":1,\"FDailyOutQtySub\":0,\"FIsEnableScheduleSub\":false},\"SubHeadEntity4\":{\"FPlanMode\":\"0\",\"FBaseVarLeadTimeLotSize\":0,\"FPlanningStrategy\":\"1\",\"FMfgPolicyId\":{\"FNumber\":\"ZZCL001_SYS\"},\"FOrderPolicy\":\"0\",\"FFixLeadTime\":0,\"FFixLeadTimeType\":\"1\",\"FVarLeadTime\":0,\"FVarLeadTimeType\":\"1\",\"FCheckLeadTime\":0,\"FCheckLeadTimeType\":\"1\",\"FOrderIntervalTimeType\":\"3\",\"FOrderIntervalTime\":0,\"FMaxPOQty\":100000,\"FMinPOQty\":0,\"FIncreaseQty\":0,\"FEOQ\":1,\"FVarLeadTimeLotSize\":1,\"FPlanIntervalsDays\":0,\"FPlanBatchSplitQty\":0,\"FRequestTimeZone\":0,\"FPlanTimeZone\":0,\"FIsMrpComBill\":true,\"FCanLeadDays\":0,\"FIsMrpComReq\":false,\"FLeadExtendDay\":0,\"FReserveType\":\"1\",\"FPlanSafeStockQty\":0,\"FAllowPartAhead\":false,\"FCanDelayDays\":999,\"FDelayExtendDay\":0,\"FAllowPartDelay\":true,\"FPlanOffsetTimeType\":\"1\",\"FPlanOffsetTime\":0,\"FWriteOffQty\":1,\"FDailyOutQty\":0},\"SubHeadEntity5\":{\"FProduceUnitId\":{\"FNumber\":\"Pcs\"},\"FFinishReceiptOverRate\":200,\"FFinishReceiptShortRate\":0,\"FProduceBillType\":{\"FNUMBER\":\"SCDD05_SYS\"},\"FOrgTrustBillType\":{\"FNUMBER\":\"SCDD06_SYS\"},\"FIsSNCarryToParent\":false,\"FIsProductLine\":false,\"FBOMUnitId\":{\"FNumber\":\"Pcs\"},\"FLOSSPERCENT\":0,\"FConsumVolatility\":0,\"FIsMainPrd\":false,\"FIsCoby\":false,\"FIsECN\":false,\"FIssueType\":\"1\",\"FOverControlMode\":\"2\",\"FMinIssueQty\":1,\"FISMinIssueQty\":false,\"FIsKitting\":false,\"FIsCompleteSet\":false,\"FStdLaborPrePareTime\":0,\"FStdLaborProcessTime\":0,\"FStdMachinePrepareTime\":0,\"FStdMachineProcessTime\":0,\"FMinIssueUnitId\":{\"FNUMBER\":\"Pcs\"},\"FStandHourUnitId\":\"3600\",\"FBackFlushType\":\"1\",\"FFIXLOSS\":0,\"FIsEnableSchedule\":false},\"SubHeadEntity7\":{\"FSubconUnitId\":{\"FNumber\":\"Pcs\"},\"FSubconPriceUnitId\":{\"FNumber\":\"Pcs\"},\"FSubBillType\":{\"FNUMBER\":\"WWDD01_SYS\"}},\"SubHeadEntity6\":{\"FCheckIncoming\":false,\"FCheckProduct\":false,\"FCheckStock\":false,\"FCheckReturn\":false,\"FCheckDelivery\":false,\"FEnableCyclistQCSTK\":false,\"FStockCycle\":0,\"FEnableCyclistQCSTKEW\":false,\"FEWLeadDay\":0,\"FCheckEntrusted\":false,\"FCheckOther\":false,\"FIsFirstInspect\":false,\"FCheckReturnMtrl\":false,\"FCheckSubRtnMtrl\":false,\"FFirstQCControlType\":\"0\"},\"FEntityInvPty\":[{\"FInvPtyId\":{\"FNumber\":\"01\"},\"FIsEnable\":true,\"FIsAffectPrice\":false,\"FIsAffectPlan\":false,\"FIsAffectCost\":false},{\"FInvPtyId\":{\"FNumber\":\"02\"},\"FIsEnable\":true,\"FIsAffectPrice\":false,\"FIsAffectPlan\":false,\"FIsAffectCost\":false},{\"FInvPtyId\":{\"FNumber\":\"03\"},\"FIsEnable\":false,\"FIsAffectPrice\":false,\"FIsAffectPlan\":false,\"FIsAffectCost\":false},{\"FInvPtyId\":{\"FNumber\":\"04\"},\"FIsEnable\":false,\"FIsAffectPrice\":false,\"FIsAffectPlan\":false,\"FIsAffectCost\":false},{\"FInvPtyId\":{\"FNumber\":\"06\"},\"FIsEnable\":false,\"FIsAffectPrice\":false,\"FIsAffectPlan\":false,\"FIsAffectCost\":false}]}}";
            //var result = client.Save(formId, Wljson);
            return View();
        }

        private object HUDNH(string fenzhu)
        {
            var shund = "";
            var client = new K3CloudApi();
            var reshund = client.QueryGroupInfo("{'FormId':'BD_MATERIAL',\"GroupFieldKey\":\"FMaterialGroup\",\"GroupPkIds\":\"\",\"Ids\":\"\"}");
            JObject jsonObject = JObject.Parse(reshund);
            JObject result = (JObject)jsonObject["Result"];
            JsonSerializerSettings settings = new JsonSerializerSettings();
            string needReturnData = JsonConvert.SerializeObject(result["NeedReturnData"], settings);
            if (needReturnData != "" || needReturnData != null)
            {
                System.Data.DataTable dt = JsonConvert.DeserializeObject<System.Data.DataTable>(needReturnData);
                //
                if (dt != null && dt.Rows.Count > 1)
                {
                    var shuji = fenzhu;
                    var HUnns = fenzhu.Split('(', ')');
                    if (HUnns.Length > 1)
                    {
                        shuji = HUnns[1];
                    }

                    var shu = dt.Select("FNUMBER like '12%' and FNAME='" + shuji + "'");
                    shund = shu[0][1].ToString();
                }
            }

            return shund;
        }

        public ActionResult DownloadExcel(int state = 0, string excelName = null, int WT_CD = 0, string Employee_path = null)
        {
            var Form = db.Formation.Where(x => x.FM_bai.Contains("WL") == false).ToList();
            if (state == 1)
            {
                ERPZDJ("ERP", Form);
                // 创建Excel文件
                ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
                using (ExcelPackage excel = new ExcelPackage())
                {
                    // 添加工作表
                    var worksheet = excel.Workbook.Worksheets.Add("Sheet1");
                    // 写入数据
                    worksheet.Cells[1, 1].Value = "物料名";
                    worksheet.Cells[1, 2].Value = "料号";
                    worksheet.Cells[1, 3].Value = "规格";
                    worksheet.Cells[1, 4].Value = "年用量";
                    worksheet.Cells[1, 5].Value = "最小起订量";
                    worksheet.Cells[1, 6].Value = "自制/外购";
                    worksheet.Cells[1, 7].Value = "一级类别";
                    worksheet.Cells[1, 8].Value = "二级类别";
                    worksheet.Cells[1, 9].Value = "表面处理";
                    worksheet.Cells[1, 10].Value = "原材料";
                    worksheet.Cells[1, 11].Value = "单位";
                    worksheet.Cells[1, 12].Value = "理论价格";
                    worksheet.Cells[1, 13].Value = "ERP未税价";
                    worksheet.Cells[1, 14].Value = "ERP含税价";
                    worksheet.Cells[1, 15].Value = "创建人";
                    worksheet.Cells[1, 16].Value = "所在单据";
                    int i = 2;

                    foreach (Formation f in Form)
                    {
                        var bian = f.FM_bai;
                        var shund = db.BOMini.Where(s => s.BOM2_bian.Contains("ERP") && s.BOM2_liao == bian).FirstOrDefault();//单行
                        var BbianH = shund == null ? "" : shund.BOM2_bian;
                        var Cxapp = db.Applications.Where(s => s.AP_bian == BbianH).FirstOrDefault();
                        if (f.FM_yj == "3")
                        {
                            f.FM_yj = "塑料";
                        }
                        int index = 1;
                        worksheet.Cells[i, index].Value = f.FM_name;
                        index++;
                        worksheet.Cells[i, index].Value = f.FM_bai;
                        index++;
                        worksheet.Cells[i, index].Value = f.FM_gg;
                        index++;
                        worksheet.Cells[i, index].Value = f.FM_nyl;
                        index++;
                        worksheet.Cells[i, index].Value = f.FM_Jieti;
                        index++;
                        worksheet.Cells[i, index].Value = f.FM_Zhuang;
                        index++;
                        worksheet.Cells[i, index].Value = f.FM_yj;
                        index++;
                        worksheet.Cells[i, index].Value = f.FM_ej;
                        index++;
                        worksheet.Cells[i, index].Value = f.FM_bmcl;
                        index++;
                        worksheet.Cells[i, index].Value = f.FM_ycl;
                        index++;
                        worksheet.Cells[i, index].Value = f.FM_ji;
                        index++;
                        worksheet.Cells[i, index].Value = f.FM_price;
                        index++;
                        worksheet.Cells[i, index].Value = f.FM_long;
                        index++;
                        worksheet.Cells[i, index].Value = f.FM_kuan;
                        index++;
                        worksheet.Cells[i, index].Value = f.FM_ms;
                        index++;
                        worksheet.Cells[i, index].Value = f.FM_kong;

                        worksheet.Row(i).Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Left;
                        worksheet.Row(i).Style.VerticalAlignment = OfficeOpenXml.Style.ExcelVerticalAlignment.Center;
                        i++;
                    }
                    worksheet.Cells["A:Z"].AutoFitColumns();
                    worksheet.Column(19).Width = 40;
                    worksheet.Column(18).Width = 40;
                    string path = "";
                    path = Server.MapPath("~/Files/");
                    excelName = "ERP物料报表";
                    DateTime now = DateTime.Now;
                    string nowtime = now.ToString("yyyy-MM-dd");
                    string Name = excelName + nowtime + ".xlsx";
                    // 确保目录存在  
                    Directory.CreateDirectory(path);

                    // 生成唯一的文件名（这里只是简单示例，你可能需要更复杂的唯一性逻辑）  
                    string fileName = Path.GetFileNameWithoutExtension(Name) + "_" + Guid.NewGuid() + Path.GetExtension(Name);

                    // 保存文件到服务器  
                    string filePath = Path.Combine(path, fileName);
                    excel.SaveAs(filePath);
                    return Json(filePath);
                }

            }
            return View();
        }
        public ActionResult WLindex(string shen = "", string ming = "", string shi = "", int shujina = 0, int state = 0, string WUliao = "")
        {
            var formation = db.Formation.Include(f => f.mateial).Include(f => f.Providers).ToList();
            formation = formation.OrderBy(s => s.FM_ID).Skip(0).Take(10).ToList();

            return View(formation);
        }
        public ActionResult delectfoer(List<Formation> formation)
        {
            int ss = 0;
            foreach (Formation f in formation)
            {
                Formation ff = db.Formation.Where(x => x.FM_bai == f.FM_bai).FirstOrDefault();
                if (ff != null)
                {
                    db.Formation.Remove(ff);
                    ss += db.SaveChanges();
                }
            }

            return Content(ss.ToString());
        }
        #region 物料成本传递到ERP
        public ActionResult Cderp(int? state)
        {
            if (state == 1)
            {
                var client = new K3CloudApi();
                //获取ERP无聊信息
                var ERPwl = db.Formation.Where(s => s.FM_bai.Contains("12.10.11.007541")).ToList();
                var Wjg = 0;
                int Jgxt = 0;
                int Gxing = 0;
                foreach (var item in ERPwl)
                {
                    var bian = item.FM_bai;

                    string formId = "BD_MATERIAL";
                    if (item.FM_price != null)
                    {
                        //参照无聊编码
                        string fieldKeys = "FMATERIALID,F_SMGS_TEXT_QTR";//名称 编码 规格 采购属性 单位 价格
                        string Filter = "FNumber like'" + bian + "%' and FUseOrgId.FNumber='10.01' ";
                        //请求参数，示例使用的是SDK提供的模板类，还可以使用字符串拼接等方式
                        var param = new QueryParam()
                        {
                            FormId = formId,
                            FieldKeys = fieldKeys,
                            FilterString = Filter,
                            TopRowCount = 0,
                            StartRow = 0,
                            Limit = 20,
                        };
                        //调用接口
                        var result = client.ExecuteBillQuery(param.ToJson());//--fanhuizhi
                        var Fmaid = int.Parse(result[0][0].ToString());
                        var HUN = result[0][1].ToString() == "TEST" || result[0][1].ToString().Trim() == "" ? "0" : result[0][1].ToString();
                        //var price = (decimal?)double.Parse(HUN);
                        if (HUN != item.FM_price.ToString())
                        {
                            string XiugaiS = "{\r\n    \"Creator\": \"\",\r\n    \"NeedUpDateFields\": [\"F_SMGS_TEXT_QTR\"],\r\n    \"NeedReturnFields\": [],\r\n    \"IsDeleteEntry\": \"true\",\r\n    \"SubSystemId\": \"\",\r\n    \"IsVerifyBaseDataField\": \"false\",\r\n    \"IsEntryBatchFill\": \"true\",\r\n    \"ValidateFlag\": \"true\",\r\n    \"NumberSearch\": \"true\",\r\n    \"InterationFlags\": \"\",\r\n    \"Model\": {\r\n        \"FMATERIALID\": " + Fmaid + ",\r\n        \"F_SMGS_TEXT_QTR\": \"" + item.FM_price + "\",\r\n    }\r\n}";
                            //--提交到ERP
                            var shu = client.Save(formId, XiugaiS);
                            var JNJI = JObject.Parse(shu);
                            var objectrf = JNJI["Result"]["Id"];
                            if (objectrf != null && objectrf.ToString() != "")
                            {
                                Gxing++;
                            }
                        }
                        else
                        {
                            Jgxt++;
                        }
                    }
                    else
                    {
                        Wjg++;
                    }

                }
                string shuchu = "无价格" + Wjg + "条,价格与ERP价格相同" + Jgxt + "条,更新" + Gxing + "条";
                return Content(shuchu);
            }
            return View();
        }
        #endregion
        #region 物料成本传递到ERP
        public ActionResult DGwlSC(List<Formation> Bian)
        {
            int state = 1;
            if (state == 1)
            {
                var client = new K3CloudApi();
                //获取ERP无聊信息
                var Wjg = 0;
                int Jgxt = 0;
                int Gxing = 0;
                foreach (var item in Bian)
                {
                    var ERPwl = db.Formation.Where(s => s.FM_bai == item.FM_bai).FirstOrDefault();
                    var bian = ERPwl.FM_bai;

                    string formId = "BD_MATERIAL";
                    if (ERPwl.FM_price != null)
                    {
                        //参照无聊编码
                        string fieldKeys = "FMATERIALID,F_SMGS_TEXT_QTR";//名称 编码 规格 采购属性 单位 价格
                        string Filter = "FNumber like'" + bian + "%' and FUseOrgId.FNumber='10.01' ";
                        //请求参数，示例使用的是SDK提供的模板类，还可以使用字符串拼接等方式
                        var param = new QueryParam()
                        {
                            FormId = formId,
                            FieldKeys = fieldKeys,
                            FilterString = Filter,
                            TopRowCount = 0,
                            StartRow = 0,
                            Limit = 20,
                        };
                        //调用接口
                        var result = client.ExecuteBillQuery(param.ToJson());//--fanhuizhi
                        var Fmaid = int.Parse(result[0][0].ToString());
                        var HUN = result[0][1].ToString() == "TEST" || result[0][1].ToString().Trim() == "" ? "0" : result[0][1].ToString();
                        //var price = (decimal?)double.Parse(HUN);
                        if (HUN != ERPwl.FM_price.ToString())
                        {
                            string XiugaiS = "{\r\n    \"Creator\": \"\",\r\n    \"NeedUpDateFields\": [\"F_SMGS_TEXT_QTR\"],\r\n    \"NeedReturnFields\": [],\r\n    \"IsDeleteEntry\": \"true\",\r\n    \"SubSystemId\": \"\",\r\n    \"IsVerifyBaseDataField\": \"false\",\r\n    \"IsEntryBatchFill\": \"true\",\r\n    \"ValidateFlag\": \"true\",\r\n    \"NumberSearch\": \"true\",\r\n    \"InterationFlags\": \"\",\r\n    \"Model\": {\r\n        \"FMATERIALID\": " + Fmaid + ",\r\n        \"F_SMGS_TEXT_QTR\": \"" + ERPwl.FM_price + "\",\r\n    }\r\n}";
                            //--提交到ERP
                            var shu = client.Save(formId, XiugaiS);
                            var JNJI = JObject.Parse(shu);
                            var objectrf = JNJI["Result"]["Id"];
                            if (objectrf != null && objectrf.ToString() != "")
                            {
                                Gxing++;
                            }
                        }
                        else
                        {
                            Jgxt++;
                        }
                    }
                    else
                    {
                        Wjg++;
                    }
                }
                string shuchu = "无价格" + Wjg + "条,价格与ERP价格相同" + Jgxt + "条,更新" + Gxing + "条";
                return Content(shuchu);
            }
            return View();
        }
        #endregion

        #region 报价系统物料同步至ERP
        public ActionResult TongBuWL(int Bian = 0)
        {
            if (Bian == 1)
            {
                var FORMa = db.Formation.Where(s => s.FM_bai.Contains("WL") && s.ZHUN == null&&s.FM_name!="N/A").ToList();
                var client = new K3CloudApi();
                foreach (var item in FORMa)
                {
                    string XiugaiS = "{\"NeedUpDateFields\":[],\"NeedReturnFields\":[],\"IsDeleteEntry\":\"true\",\"SubSystemId\":\"\",\"IsVerifyBaseDataField\":\"false\",\"IsEntryBatchFill\":\"true\",\"ValidateFlag\":\"true\",\"NumberSearch\":\"true\",\"IsAutoAdjustField\":\"true\",\"InterationFlags\":\"\",\"IgnoreInterationFlag\":\"\",\"IsControlPrecision\":\"false\",\"ValidateRepeatJson\":\"false\",\"IsAutoSubmitAndAudit\":\"true\",\"Model\":{\"FID\":0,\"FNumber\":\"" + item.FM_bai + "\",\"FName\":\"" + item.FM_name + "\",\"F_SMGS_Text_qtr\":\"" + item.FM_ID + "\"}}";
                    var shu = client.Save("SMGS_BJWL", XiugaiS);
                    item.ZHUN = 1;
                    db.Entry(item).State = EntityState.Modified;
                    db.SaveChanges();
                }
                return Content("shuchu");
            }
            return View();
        }
        #endregion

        #region 查询星空物料信息并创建行的ERP成本单
        public ActionResult ErpWL(int stast = 0, string ren = "")
        {
            if (stast == 1)
            {

                K3CloudApi client = new K3CloudApi();
                string Filter = "F_SMGS_Base_83g.FNumber <>'' and FForbidStatus='A' and FDocumentStatus='C' and FCreateOrgId.FNumber='10.01'";
                //请求参数，示例使用的是SDK提供的模板类，还可以使用字符串拼接等方式 FEntryExpiryDate
                var param = new QueryParam()
                {
                    FormId = "BD_MATERIAL",
                    FieldKeys = "FNumber,F_SMGS_Base_qtr.FNumber",
                    FilterString = Filter,
                    TopRowCount = 0,
                    StartRow = 0,
                    Limit = 500,
                };
                //调用接口
                var result = client.ExecuteBillQuery(param.ToJson());
                if (result.Count() == 0)
                {
                    return Content("wu");
                }
                else
                {
                    foreach (var item in result)
                    {
                        //同步数量
                        var bian = item[1].ToString();
                        var bian1 = item[0].ToString();
                        var lioas = db.Formation.Where(s => s.FM_bai == bian1).FirstOrDefault();
                        if (lioas != null)
                        {
                            continue;
                        }
                        else
                        {
                            var shjn = db.Formation.Where(s => s.FM_bai == bian).FirstOrDefault();
                            if (shjn == null)
                            {
                                continue;
                            }
                            else
                            {
                                //创建单据
                                var shu = AC.CJAPP(ren);
                                //创建BOM
                                var SHUN = AC.CJBOM(shu, item[1].ToString(), item[0].ToString());
                                //保存物料
                                var NMJk = AC.WULIAO(item[1].ToString(), item[0].ToString(), SHUN);
                                //输出
                            }
                        }
                    }
                    return Content("ASC");
                }
            }
            return View();
        }
        #endregion
    }
}
